import os
import pandas as pd
from dotenv import load_dotenv
from py2neo import Graph

# 加载环境变量
load_dotenv()

# Neo4j 连接
NEO4J_URI = os.getenv("NEO4J_URI")
NEO4J_USER = os.getenv("NEO4J_USER")
NEO4J_PASSWORD = os.getenv("NEO4J_PASSWORD")

# 直接建立连接
graph = Graph(NEO4J_URI, auth=(NEO4J_USER, NEO4J_PASSWORD))
# 测试连接
print("✅ 连接Neo4j成功" if graph.run("RETURN 1").data() else "❌ 连接Neo4j失败")

# 定义要处理的CSV文件列表
csv_files = [
    "out-辅料匹配结果.csv",
    "out-设备匹配结果.csv",
    "out-制造资源匹配结果.csv"
]

# 初始化总更新节点数
total_count = 0

# 遍历每个CSV文件
for csv_file in csv_files:
    # 用pandas读取CSV
    df = pd.read_csv(csv_file)

    # 遍历数据并更新节点
    for _, row in df.iterrows():
        node_id = int(row["neo4j_ID"])
        mpm_id = row["standard_编码"]
        mpm_type = row["type"]
        mpm_modelDefinition = row["modelDefinition"]
        
        # 执行更新操作
        graph.run(
            "MATCH (n) WHERE id(n) = $id SET n.mpm_id = $mpm_id, n.mpm_type = $mpm_type, n.mpm_modelDefinition = $mpm_modelDefinition",
            id=node_id,
            mpm_id=mpm_id,
            mpm_type=mpm_type,
            mpm_modelDefinition=mpm_modelDefinition
        )
        total_count += 1
        print(f"更新节点 {node_id}，mpm_id 为 {mpm_id}")

print(f"🎉 处理完成，共更新 {total_count} 个节点")
